import urllib
import re

from waveapi import events
from waveapi import model
from waveapi import robot

from django.utils import simplejson
from google.appengine.api import urlfetch

def OnRobotAdded(properties, context):
    wavelet = context.GetRootWavelet()
    wavelet.CreateBlip().GetDocument().SetText('y0!')

def OnBlipSubmitted(properties, context):
    wavelet = context.GetRootWavelet()
    blip = context.GetBlipById(properties['blipId'])
    content = blip.GetDocument().GetText()
    """Do a search"""
    if content.startswith("search "):
        query = blip.GetDocument().GetText().replace("search ", "")
        if query:
            doSearch(query, context)
        else:
            wavelet.CreateBlip().GetDocument().SetText('Cari apa geng?')
    elif content.startswith("tolong"):
        doHelp(context)

def doSearch(query, context):
    wavelet = context.GetRootWavelet()
    wavelet.CreateBlip().GetDocument().SetText('Tunggu kejap. Gua tengah cari...')
    """Search"""        
    results = ""
    url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&start=0&q=%s' % (urllib.quote(query))
    results_content = urlfetch.fetch(url=url).content
    for item in simplejson.loads(results_content)['responseData']['results']:
        p = re.compile('<[/ ]?[a-zA-Z ]>')
        title = p.sub('',item['title'])
        content = p.sub('',item['content'])
        returnStr = title + '\n' + item['url'] + '\n' + content + '\n\n'
        results += returnStr
    """Return results"""  
    if results:
        wavelet.CreateBlip().GetDocument().SetText('Gua dah dapat result dah...\n\n' + results)
    else:
        wavelet.CreateBlip().GetDocument().SetText('Tak jumpa apa pun geng. Lu cari benda betul ke?')
        
def doTranslate(blip, context):
    wavelet = context.GetRootWavelet()
    content = blip.GetDocument().GetText()
    """Translate"""
    wavelet.CreateBlip().GetDocument().SetText('Fuyoh... jap tengah translate ni...')
    """Return translation"""
    """No translation"""
    wavelet.CreateBlip().GetDocument().SetText('Bahasa apa ni geng? Gua tak faham...')

def doMapSearch(blip, context):
    wavelet = context.GetRootWavelet()
    """Search map"""
    wavelet.CreateBlip().GetDocument().SetText("Lokasi di cari...")
    """Return map results"""
    """No map results"""
    wavelet.CreateBlip().GetDocument().SetText("Tak jumpa la geng. Wujud ke tempat ni?")
    
def doHelp(context):
    wavelet = context.GetRootWavelet()
    wavelet.CreateBlip().GetDocument().SetText('Yes brader?\n\n'
    '"search <keywords>" untuk cari benda menarik...\n'
    '"translate <from_language> <to_language> <text_to_translate>" untuk cakap bahasa orang lain...\n'
    '"map <street_address_city_country>" untuk cari lokasi dalam peta...\n'
    'Ok geng? Gua ciao dulu.\n') 
    
if __name__ == '__main__':
    roboto = robot.Robot('GuaRockYou',
                             image_url='http://guarockyou.appspot.com/assets/icon.jpg',
                             version='3.2.3',
                             profile_url='http://guarockyou.appspot.com/')
    roboto.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)
    roboto.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
    roboto.Run()